//个人中心首页
var app = getApp(); //全局APP

Page({
	//页面初始数据
	data: {
		nickname: '请绑定账号',
		btnName: '解除绑定',
		avatar: '../../image/default_avatar.png',
		isLogin: false,
		btnDisabled: false // 按钮是否可用
	},

	//加载执行
	onShow: function(options) {
		var page = this;

		var userToken = app.db.get('userToken');
		if (!userToken) {
			page.setData({
				btnName: '绑定',
				isLogin: false
			});

			//app.common.jumpToLogin();
		} else {
			page.setData({
				btnName: '解除绑定',
				isLogin: true
			});
			
			app.api.userInfo(function(res) {
				if (res.status) {
					//如果没有头像，设置本地默认头像
					var avatar = '../../image/default_avatar.png';
					if (res.data.avatar) {
						avatar = res.data.avatar;
					}
					page.setData({
						nickname: res.data.nickname,
						avatar: avatar,
						balance: res.data.balance,
						bindingbalance: res.data.bindingbalance,
					});
				}
			});
		}


		page.setData({
			btnDisabled: false
		});
	},
	
	handleMove(e){
		//不做任何处理
	},
	
	//设置用户信息
	modifyPwd: function() {
		if(this.data.isLogin == false) {
			app.common.errorToBack('请先绑定账号', 0);
			return;
		}
		
		wx.navigateTo({
			url: '../modifyPwd/modifyPwd'
		});
	},

	//解除绑定
	logout: function() {
		var page = this;

		if (this.data.btnName == "绑定") {
			app.common.jumpToLogin();
		} else {
			wx.showModal({
				title: '提示',
				content: '确认解除绑定吗？',
				success: function(res) {
					if (res.confirm) {

						page.setData({
							btnDisabled: true
						});

						var data = {};

						// 请求解除绑定
						app.api.logout(data, function(logoutRes) {
							if (logoutRes.status) {
								app.common.successToShow('解除绑定成功!', function() {
									wx.removeStorageSync('jump_to_login');
									wx.removeStorageSync('userToken');
									wx.removeStorageSync('myInviteCode');
									wx.switchTab({
										url: '/pages/index/index'
									});
								});
							} else {
								//报错了
								app.common.errorToBack(logoutRes.msg, 0);

								page.setData({
									btnDisabled: false
								});
							}
						});
					}
				}
			})
		}
	}
});
